import logger
from django.shortcuts import render
from .models import User, Item
from django.http import JsonResponse
from django.db.models import Q, Sum, Max, Min, Count
from django.core.cache import cache
from django.core.signing import Signer
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.forms.models import model_to_dict
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from datetime import timedelta
import base64, string, random
# Create your views here.


def is_empty(c):
    return c is None or str(c).strip() == ''

def base64password(password):
    bp = bytes(password, encoding='utf-8')
    b64p = base64.b64encode(bp).decode('utf-8')
    return b64p

def createtoken(name):
    randomtoken = ''.join(random.choices(string.ascii_letters, k=8))
    token = Signer().sign(randomtoken+name)
    cache.set(f'test_{name}', token, timeout=timedelta(minutes=100).total_seconds())
    return token

def chacktoken(request):
    gettoken = request.META.get('HTTP_TOKEN')
    if is_empty(gettoken):
        return False, '请先登录！'
    unsigntoken = Signer().unsign(gettoken)
    name = unsigntoken[8:]
    cachetoken = cache.get(f'test_{name}')
    if is_empty(cachetoken):
        return False, '缓存中无token，token已失效'
    return True, name

@api_view(['post'])
def register(request):
    data = JSONParser().parse(request)

    username = data.get('username')
    password = data.get('password')

    if is_empty(username):
        return JsonResponse({
            'message': '用户名不能为空或不存在'
        }, status=400)

    if is_empty(password):
        return JsonResponse({
            'message': '密码不能为空或不存在'
        }, status=400)

    if User.objects.filter(username=username).exists():
        return JsonResponse({
            'message': '该用户已存在！'
        }, status=404)

    try:
        User(username=username, password=base64password(password)).save()

        return JsonResponse({
            'message': f'用户{username}注册成功'
        })
    except Exception as e:
        return JsonResponse({
            'message': f'注册失败，内部错误：{e}'
        }, status=500)


@api_view(['post'])
def login(request):
    data = JSONParser().parse(request)

    username = data.get('username')
    password = data.get('password')

    if is_empty(username):
        return JsonResponse({
            'message': '用户名不能为空或不存在'
        }, status=400)

    if is_empty(password):
        return JsonResponse({
            'message': '密码不能为空或不存在'
        }, status=400)

    if User.objects.filter(username=username).exists() is False:
        return JsonResponse({
            'message': '用户不存在，请先注册！'
        },status=404)
    try:
        if User.objects.get(username=username).password == base64password(password):
            token = createtoken(username)
            return JsonResponse({
                'message': '登录成功',
                'token': token
            }, status=200)
        else:
            return JsonResponse({
                'message': '密码错误或格式不正确！'
            }, status=404)
    except Exception as e:
        return JsonResponse({
            'message': f'登录失败，内部错误：{e}'
        }, status=500)


# 物品发布
@api_view(['post'])
def publish(request):
    # 验证用户是否登录，保存物品信息
    flag, name = chacktoken(request)
    if flag is False:
        return JsonResponse({
            'message': name
        }, status=401)

    data = JSONParser().parse(request)

    title = data.get('title')
    price = data.get('price')
    userid = data.get('userid')

    if is_empty(title):
        return JsonResponse({
            'message': '物品标题不能为空或不存在'
        }, status=400)

    if is_empty(price):
        return JsonResponse({
            'message': '物品价格不能为空或不存在'
        }, status=400)

    try:
        Item(title=title, price=price, seller_id_id=userid).save()

        return JsonResponse({
            'message': f'物品{title}发布成功'
        })
    except Exception as e:
        return JsonResponse({
            'message': f'发布失败，内部错误：{e}'
        }, status=500)



# 物品浏览
@api_view(['get'])
def list(request):

    flag, name = chacktoken(request)
    if flag is False:
        return JsonResponse({
            'message': name
        }, status=401)

    page = request.GET.get('page')
    page_size = request.GET.get('page_size')

    try:
        objallitem = Item.objects.filter(status='available')
        objpageall = Paginator(objallitem, page_size)

        try:
            objpage = objpageall.page(page)
        except PageNotAnInteger:
            objpage = objpageall.page(1)
        except EmptyPage:
            objpage = objpageall.page(objpageall.num_pages)

        lis = []
        for obj in objpage.object_list:
            lis.append({
                'id':obj.id,
                'title': obj.title,
                'price': obj.price,
                'userid': obj.seller_id.id,
                'username': obj.seller_id.username,
            })

        return JsonResponse({
            'message': '查询成功',
            'code': 200,
            'items': objallitem.count(),
            'data': lis
        })


    except Exception as e:
        return JsonResponse({
            'message': f'查询失败，内部错误：{e}'
        }, status=500)



# 物品购买
@api_view(['post'])
def buy(request):

    flag, name = chacktoken(request)
    if flag is False:
        return JsonResponse({
            'message': name
        }, status=401)

    data = JSONParser().parse(request)
    item_id = data.get('item_id')

    if is_empty(item_id):
        return JsonResponse({
            'message': '物品ID为必填参数，不能为空或不存在'
        }, status=400)

    try:
        obj = Item.objects.get(id=item_id)
        obj.status = 'sold'
        obj.save()
        return JsonResponse({
            'message': '修改成功'
        })
    except Exception as e:
        return JsonResponse({
            'message': f'修改失败，内部错误：{e}'
        }, status=500)



